<?php

namespace App\W7OpenTracing;

use OpenTracing\Reference;
use OpenTracing\Span;
use OpenTracing\SpanContext;
use OpenTracing\StartSpanOptions;
use OpenTracing\Tracer;
use const OpenTracing\Formats\TEXT_MAP;

class Facade
{
    /**
     * @return \OpenTracing\Tracer
     */
    public static function tracer(): Tracer
    {
        return app()->make(Tracer::class);
    }

    public static function flush(): void
    {
        self::tracer()->flush();
    }

    public static function carrierFromRequest(\Illuminate\Http\Request $request = null): array
    {
        return Carrier::fromRequest($request);
    }

    public static function carrierToSpanContext(array $carrier): ?\OpenTracing\SpanContext
    {
        return self::tracer()->extract(TEXT_MAP, $carrier);
    }

    public static function startSpanCarrier($operationName, $carrier): Span
    {
        $spanContext = self::carrierToSpanContext($carrier);

        return self::tracer()->startSpan($operationName, ['child_of' => $spanContext]);
    }

    public static function startSpanChildOf($operationName, SpanContext $spanContext): Span
    {
        return self::tracer()->startSpan($operationName, ['child_of' => $spanContext]);
    }

    public static function startSpanFollowsFrom($operationName, Span $span): Span
    {
        $options = StartSpanOptions::create([
            'references' => Reference::createForSpan(Reference::FOLLOWS_FROM, $span),
        ]);

        return self::tracer()->startSpan($operationName, $options);
    }
}
